package util

import (
	"github.com/google/uuid"
	"github.com/hashicorp/consul/api"
	"log"
	"strconv"
)

var client *api.Client
var ServiceName string
var ServicePort int
var ServiceId string

func init() {
	config := api.DefaultConfig()
	config.Address = "192.168.3.127:8500"
	//
	var err error
	client, err = api.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}
	ServiceId = "userService" + uuid.New().String()
}

func SetServiceNameAndPort(name string, port int) {
	ServiceName = name
	ServicePort = port
}
func RegService() {
	registration := api.AgentServiceRegistration{}
	registration.Name = ServiceName
	registration.ID = ServiceId
	registration.Address = "192.168.3.27"
	registration.Port = ServicePort
	registration.Tags = []string{"primary", "v1"}

	registration.Check = &api.AgentServiceCheck{
		HTTP:     "http://192.168.3.27:" + strconv.Itoa(ServicePort) + "/health",
		Interval: "10s",
		Timeout:  "5s",
	}
	registration.Weights = &api.AgentWeights{
		Passing: 10,
		Warning: 1,
	}

	err := client.Agent().ServiceRegister(&registration)
	if err != nil {
		log.Fatal(err)
	}
}

func DeRegService() {
	client.Agent().ServiceDeregister(ServiceId)
}
